package com.hht.downloadmanager.net;

import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class OkHttpUtils {

    private OkHttpClient mOkHttpClient;
    private final static long CONNECT_TIMEOUT = 60;//超时时间，秒
    private final static long READ_TIMEOUT = 60;//读取时间，秒
    private final static long WRITE_TIMEOUT = 60;//写入时间，秒

    public OkHttpUtils() {
        //创建okHttpClient对象
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS).build();
    }

    public static OkHttpUtils getInstance() {
        return InitHttpUtil.INSTALL;
    }

    private static class InitHttpUtil {
        private static OkHttpUtils INSTALL = new OkHttpUtils();
    }


    /**
     * @param fileUil  文件的下载址
     * @param callback 回调
     */
    public void getFileContentLength(String fileUil, Callback callback) {
        Request request = new Request.Builder()
                .url(fileUil)
                .build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    /**
     * @param fileUil    下载链接
     * @param startIndex 下载起始位置
     * @param endIndex   结束为止
     * @param callback   回调
     */
    public void downLoadFileByRange(String fileUil, long startIndex, long endIndex, Callback callback) {
        // 创建一个Request
        // 设置分段下载的头信息。 Range:做分段数据请求,断点续传指示下载的区间。格式: Range bytes=0-1024或者bytes:0-1024
        Request request = new Request.Builder().header("RANGE", "bytes=" + startIndex + "-" + endIndex)
                .url(fileUil)
                .build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }
}
